<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 2017/9/5
 * Time: 17:04
 */

namespace app\admin\controller;


use app\admin\model\AuthGroupModel;
use think\Request;
use app\admin\model\MenuModel;

class AuthGroup extends Common
{

    protected $auth_group_model;

    public function __construct() {
        parent::__construct();
        /* @var $menu_model \app\admin\model\MenuModel */

        $auth_group_model = new AuthGroupModel();
        $this->auth_group_model = $auth_group_model;
    }

    /**
     * 角色列表
     */
    public function authGroupList() {
        /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */
        $data = $this->auth_group_model->getGroupList();

        $this->view->assign('nav1','系统管理');
        $this->view->assign('nav2','角色管理');
        $this->assign('list', $data['list']);
        $this->assign('page', $data['page']);
        $this->assign('pageCount', $data['count']);
        return $this->fetch();
    }

    /**
     * 添加角色页面显示
     */
    public function addGroup() {
        if (Request::instance()->isPost()) {
            $params = array(
                'id' => uuid(),
                'title' => input('title'),
                'status' => 0,
                'rules' => '',
            );
            if (!$params['title']) {
                parent::ajaxError('请输入角色名称!');
            }

            /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

            $add_group_result = $this->auth_group_model->insert($params);
            if (!$add_group_result) {
                parent::ajaxError('添加失败!');
            }
            parent::ajaxSuccess('添加成功!');
        } else {
            return $this->fetch();
        }

    }


    /**
     * 编辑角色页面显示
     */
    public function editGroup() {
        if (Request::instance()->isPost()) {
            $params = array(
                'id' => input('id'),
                'title' => input('title'),
            );
            if (!$params['id']) {
                parent::ajaxError('角色不存在!');
            }
            if (!$params['title']) {
                parent::ajaxError('请输入角色名称!');
            }
            /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

            $save_group_result = $this->auth_group_model->update($params);
            if ($save_group_result === false) {
                parent::ajaxError('修改失败!');
            }
            parent::ajaxSuccess('修改成功!');
        } else {
            $id = input('id');
            /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

            $group_info = $this->auth_group_model->findGroup($id);

            $this->assign('group_info', $group_info);
            return $this->view->fetch();
        }

    }

    /**
     * 删除角色处理
     */
    public function deleteGroup() {
        $id = input('id');
        if (!$id) {
            parent::ajaxError('角色不存在!');
        }
        if($id == 1) parent::ajaxError('系统管理员不允许删除');

        /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

        $group_info = $this->auth_group_model->findGroup($id);
        if (!$group_info) {
            parent::ajaxError('角色不存在!');
        }
        $change_result = $this->auth_group_model->changeResult($id, 2);
        if ($change_result === false) {
            parent::ajaxError('删除失败!');
        }
        parent::ajaxSuccess('删除成功!');
    }

    /**
     * 分配角色
     */
    public function giveRole() {
        if (Request::instance()->isPost()) {
            $user_id = input('user_id');
            if (!$user_id) {
                parent::ajaxError('用户不存在!');
            }

            $group_id = $_POST['group_id'];
            //html_entity_decode($string)
            /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */
            $auth_group_access_model = new AuthGroupAccessModel();

            if (!empty($group_id)) {
                //删除原有角色
                $auth_group_access_model->where(array('uid' => $user_id))->delete();
                foreach ($group_id as $v) {
                    $add_data = array(
                        'uid' => $user_id,
                        'group_id' => $v,
                    );
                    $auth_group_access_model->insert($add_data);
                }
            }
            parent::ajaxSuccess('分配成功!');
        } else {
            $user_id = input('user_id');

            /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

            $data = $this->auth_group_model->getGroupList($user_id);

            $this->assign('list', $data['list']);
            $this->assign('user_id', $user_id);
            $this->assign('pageCount', $data['count']);
            return $this->view->fetch();
        }
    }

    /**
     * 分配权限
     */
    public function ruleGroup() {
        /* @var $admin_auth_group_model \Admin\Model\AdminAuthGroupModel */

        if (Request::instance()->isPost()) {
            //$id = input('post.role_id');
            $data = input('post.');
            show_bug($data);die;//Request::instance()->param()

            /*if (!count($data)) {
                $data = array();
            }*/
            $rule_ids = "";
            foreach ($data['node_id'] as $k => $v){
                $tmp = explode("__", $v);
                if ($k == count($data['node_id'])-1){
                    $rule_ids .= $tmp[0];
                }else{
                    $rule_ids .= $tmp[0].",";
                }



            }


            if (!$rule_ids) {
                $this->ajaxError('请选择需要分配的权限');
            }

            if ($this->auth_group_model->addAuthRule($rule_ids, $data['role_id']['role_id']) !== false) {
                $this->ajaxSuccess('分配成功');
            } else {
                $this->ajaxError('分配失败，请检查');
            }

        } else {

            $role_id = input('get.role_id');
            /* @var $menu_model \Admin\Model\AdminMenuModel */
            $menu_model = new MenuModel();
            $menuList = $menu_model->selectAllMenu(2);

            //$menus = get_column($menuList, 2);
            //show_bug($menus);die;
            $role_info = $this->auth_group_model->findGroup($role_id);
            $rulesArr = [];

            if ($role_info['rules']) {
                $rulesArr = explode(',', $role_info['rules']);

                $this->assign('rulesArr', $rulesArr);
            } else {
                $rulesArr = array();
                $this->assign('rulesArr', array());
            }

            //生成wdTree插件需要的数据格式
            $node_tree = [];
            foreach ($menuList as $v) {
                $node_tree[] = [
                    "id"          => $v['id'],
                    "pid"         => $v['pid'],
                    "text"        => $v['title'] . " (" . $v['url'] . ") ",
                    "value"       => $v['id'] . "_" . $v['level'] . "_" . $v['pid'],
                    "showcheck"   => true,
                    'checkstate'  => in_array($v['id'], $rulesArr) ? 1 : 0,
                    'hasChildren' => $v['type'] ? true : false,
                    'isexpand'    => true,
                    'complete'    => true,
                ];
            }

            //生成树
            $menus =  list_to_WDTree($node_tree, "id", "pid", "ChildNodes");
            $this->view->assign('menus',array());
            $this->view->assign("tree", json_encode($menus));
            $this->view->assign('role_id', $role_id);
            return $this->view->fetch();
        }
    }



}